<template>
  <div ref="sceneContainer" class="scene-container"></div>
</template>

<script>
import * as THREE from 'three';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'; // 引入OrbitControls
import * as dat from 'dat.gui'; // 引入dat.gui
import * as TWEEN from '@tweenjs/tween.js';

export default {
  name: 'ShipModel',
  data() {
    return {
      tilt: {
        x: 0,
        y: 0,
        z: 0
      },
      position: {  // 新增模型位置数据
        x: 0,
        y: 0,
        z: 0
      },
      targetTilt: {
        x: 0,
        y: 0,
        z: 0
      },
      gui: null, // 用于存储dat.gui实例
      lastUpdateTime: Date.now() // 记录上次更新时间
    };
  },
  mounted() {
    this.init3DScene();
  },
  beforeUnmount() { // Vue 2 使用 beforeDestroy，Vue 3 使用 beforeUnmount
    if (this.gui) {
      this.gui.destroy();
    }
    TWEEN.removeAll();
  },
  methods: {
    init3DScene() {
      // 场景、相机、渲染器
      const scene = new THREE.Scene();

      const camera = new THREE.PerspectiveCamera(75, this.$refs.sceneContainer.clientWidth / this.$refs.sceneContainer.clientHeight, 0.1, 1000);
      const renderer = new THREE.WebGLRenderer();

      // 设置背景颜色为白色
      renderer.setClearColor(0xffffff, 1);

      // 使用容器尺寸而不是window尺寸
      renderer.setSize(this.$refs.sceneContainer.clientWidth, this.$refs.sceneContainer.clientHeight);
      this.$refs.sceneContainer.appendChild(renderer.domElement);

      // 添加光源
      const light = new THREE.AmbientLight(0xffffff, 1);
      scene.add(light);

      // 加载背景图片
      const textureLoader = new THREE.TextureLoader();
      textureLoader.load('/images/sea.jpg', (texture) => {
        scene.background = texture;
      });

      // 加载船舶模型
      const loader = new GLTFLoader();
      let model;
      loader.load(
        '/model/boat.glb', // 这里替换成你的船舶模型路径
        (gltf) => {
          model = gltf.scene;
          scene.add(model);

          // 调整模型位置和缩放
          model.scale.set(1, 1, -1);
          model.position.set(2, -2, 0);

          // 视角控制（OrbitControls）
          const controls = new OrbitControls(camera, renderer.domElement);
          controls.enableDamping = true; // 开启阻尼，平滑过渡
          controls.dampingFactor = 0.25; // 设置阻尼系数
          controls.screenSpacePanning = false; // 防止上下旋转导致的坐标问题
          controls.maxPolarAngle = Math.PI / 2; // 限制上下旋转角度，防止模型倒立

          // 设置相机初始视角偏左上角
          camera.position.set(5, 3, 7); // 将相机设置在船的前方偏左上方位置
          camera.lookAt(model.position); // 让相机朝向船的模型位置

          // 判断gui是否已经存在，不存在则创建
          if (!this.gui) {
            this.gui = new dat.GUI();
            this.$nextTick(() => {
              if (this.gui && this.gui.domElement) {
                // 获取容器位置
                const containerRect = this.$refs.sceneContainer.getBoundingClientRect();
                
                // 调整 GUI 组件的位置
                this.gui.domElement.style.position = 'absolute';
                this.gui.domElement.style.top = `${containerRect.top}px`; // 距离顶部20px
                this.gui.domElement.style.left = `${containerRect.left}px`; // 距离左侧20px
                this.gui.domElement.style.zIndex = '1000';

                // 调整背景色
                this.gui.domElement.style.backgroundColor = 'rgba(0, 0, 0, 0.2)'; // 黑色背景，70% 透明度
                // 调整字体颜色
                const labels = this.gui.domElement.querySelectorAll('.property-name');
                labels.forEach(label => {
                  label.style.color = '#ff5722'; // 白色字体
                });

                const inputs = this.gui.domElement.querySelectorAll('input');
                inputs.forEach(input => {
                  input.style.color = 'orange'; // 白色字体
                });

                // 调整滑块颜色
                const sliders = this.gui.domElement.querySelectorAll('.slider');
                sliders.forEach(slider => {
                  slider.style.backgroundColor = 'orange'; // 滑块背景色
                });

                const sliderFgs = this.gui.domElement.querySelectorAll('.slider-fg');
                sliderFgs.forEach(sliderFg => {
                  sliderFg.style.backgroundColor = '#ff5722'; // 滑块前景色（橙色）
                });
              }
            });
            // 修改旋转控制器的名称
            const xController = this.gui.add(this.tilt, 'x', -Math.PI / 4, Math.PI / 4, 0.01)
              .name('rotation(x)')
              .onChange(() => {
                if (model) {
                  model.rotation.x = this.tilt.x;
                }
              });
            const yController = this.gui.add(this.tilt, 'y', -Math.PI / 4, Math.PI / 4, 0.01)
              .name('rotation(y)')
              .onChange(() => {
                if (model) {
                  model.rotation.y = this.tilt.y;
                }
              });
            const zController = this.gui.add(this.tilt, 'z', -Math.PI / 4, Math.PI / 4, 0.01)
              .name('rotation(z)')
              .onChange(() => {
                if (model) {
                  model.rotation.z = this.tilt.z;
                }
              });

            // 修改位置控制器的名称
            const posXController = this.gui.add(this.position, 'x', -10, 10, 0.1)
              .name('position(x)')
              .onChange(() => {
                if (model) {
                  model.position.x = this.position.x;
                }
              });
            const posYController = this.gui.add(this.position, 'y', -10, 10, 0.1)
              .name('position(y)')
              .onChange(() => {
                if (model) {
                  model.position.y = this.position.y;
                }
              });
            const posZController = this.gui.add(this.position, 'z', -10, 10, 0.1)
              .name('position(z)')
              .onChange(() => {
                if (model) {
                  model.position.z = this.position.z;
                }
              });
          }

          // 渲染循环
          const animate = () => {
            requestAnimationFrame(animate);
            controls.update(); // 使得控制器更新

            // 每秒更新一次随机旋转
            const currentTime = Date.now();
            if (currentTime - this.lastUpdateTime >= 500) {
              this.tilt.x = (Math.random() - 0.5) * Math.PI / 50;
              this.tilt.y = (Math.random() - 0.5) * Math.PI / 50;
              this.tilt.z = (Math.random() - 0.5) * Math.PI / 50;
              if (model) {
                model.rotation.x = this.tilt.x;
                model.rotation.y = this.tilt.y;
                model.rotation.z = this.tilt.z;
              }
              // 更新dat.gui中的值
              if (this.gui) {
                this.gui.__controllers.forEach(controller => {
                  controller.updateDisplay();
                });
              }
              this.lastUpdateTime = currentTime;
            }

            renderer.render(scene, camera);
            // 实时打印相机位置
            // console.log(`相机位置: x=${camera.position.x}, y=${camera.position.y}, z=${camera.position.z}`);
          };
          animate();
        },
        undefined,
        (error) => {
          console.error('模型加载出错:', error);
        }
      );
      // 修改窗口resize事件处理
      window.onresize = () => {
        const container = this.$refs.sceneContainer;
        renderer.setSize(container.clientWidth, container.clientHeight);
        camera.aspect = container.clientWidth / container.clientHeight;
        camera.updateProjectionMatrix();
      };
    }
  }
}
</script>

<style scoped>
.scene-container {


  width: 500px;  /* 调整为100%宽度 */
  height: 100%; /* 设置固定高度或使用百分比 */
}





</style>